# coding: utf-8
import os
import logging
from datetime import datetime
import allure
import allure_commons
import pytest
from _pytest.config import Config
from _pytest.logging import LogCaptureHandler
from page.base.BaseDriver import BaseDriver
from config.GlobalVar import G
from handler.AllureLogStepHandler import AllureLogStepHandler
from utils.OsUtil import mk_dir

pageobject = None
context = None
base_driver = None


# pytest配置对象
# 注意此对象只能在顶层目录的conftest.py文件中完成
# action：store 存储参数
# default 参数默认值，此处为“device”
# help 参数帮助信息，此处为无
def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store", default="device", help="None")


# 解析命令行
@pytest.fixture(scope="class")
def cmdopt(request):
    return request.config.getoption("--cmdopt")


@pytest.fixture(scope="class")
def page(cmdopt):
    global base_driver
    if base_driver is None:
        base_driver = BaseDriver(eval(cmdopt))  # eval将字符串转换为字典
    driver = base_driver.get_base_driver()  # 公共的driver
    yield driver
    driver.quit()

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取每个用例状态的钩子函数
    :param item: 测试用例
    :param call: 测试步骤
    :return:
    """
    # 获取钩子方法的调用结果
    global pageobject
    out_come = yield
    path = os.path.join(G.SCREENSHOT_DIR, datetime.now().strftime("%Y%m%d"))
    mk_dir(path)
    rep = out_come.get_result()  # 从钩子方法的调用结果中获取测试报告
    # rep.when表示测试步骤，仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
    if rep.when == "call":
        if rep.failed:
            # 添加allure报告截图
            if hasattr(pageobject, "screenshot"):
                with allure.step('添加失败截图...'):
                    path = os.path.join(path, f"{datetime.now().strftime('%H%M%S')}_{item.name}_失败截图.png")
                    file = pageobject.screenshot(path=path, full_page=True)
                    # 使用allure自带的添加附件的方法,三个参数分别为：源文件、文件名、文件类型
                    allure.attach(file, "失败截图", allure.attachment_type.PNG)
        else:
            if hasattr(pageobject, "screenshot"):
                # 添加allure报告截图
                with allure.step("添加执行完毕截图......"):
                    path = os.path.join(path, f"{datetime.now().strftime('%H%M%S')}_{item.name}_成功截图.png")
                    file = pageobject.screenshot(path=path, full_page=True)
                    # 使用allure自带的添加附件的方法,三个参数分别为：源文件、文件名、文件类型
                    allure.attach(file, "执行完毕截图", allure.attachment_type.PNG)


@pytest.hookimpl(trylast=True)
def pytest_configure(config: Config):
    """
    初始配置钩子，自定义allure日志采集器
    """
    logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
    handler = LogCaptureHandler()
    handler.setFormatter(logging_plugin.formatter)
    # handler.setLevel(logging_plugin.log_level)
    logger = logging.getLogger()
    logger.addHandler(handler)
    step_plugin = AllureLogStepHandler(handler)
    allure_commons.plugin_manager.register(step_plugin)

    def unregister_plugin(plugin):
        def unregister():
            allure_commons.plugin_manager.unregister(plugin)

        return unregister

    config.add_cleanup(unregister_plugin(step_plugin))
